package main.java.pers.seg.model.utils;

import main.java.pers.seg.model.constants.PathConstants;
import main.java.pers.seg.model.model.TargetInteractionFlow;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

//import javax.persistence.criteria.CriteriaBuilder;
import java.io.File;
import java.util.*;


public class FlowUtils {
    public static List<TargetInteractionFlow> targetInteractionFlowList = new ArrayList<>();

    /**
     * 这个方法可以读取xml文件后给每个元素添加一个index属性，并返回一个map
     * 这个map下存的是这个xml的所有元素，你可以通过索引来获取
     * 比如：（Element）map.get("0123")可以获取到根节点下第一个元素的第二个子元素的第三个子元素。
     * (Document)map.get("document")可以获取document对象。
     * @param filePath 要读取的xml文件的路径
     * @return
     * @throws Exception
     */
    public static Map<String,Node> getMap(String filePath) throws Exception {
        if (filePath==null || filePath.isEmpty()){
            throw new Exception("filePath could not be null or empty!");
        }
        File file = new File(filePath);
        if(!file.exists() || !file.isFile() || !(file.getName().endsWith(".xml") || file.getName().endsWith(".core"))){
            throw new Exception(filePath+" is not a xml file");
        }
        if (!file.canRead()){
            throw new Exception("can not read "+filePath);
        }
        SAXReader reader = new SAXReader();
        Map<String,Node> map = new HashMap<String,Node>();
        try {
            Document document = reader.read(file);
            Element root = document.getRootElement();
            map.put("document",document);
            List<Element> elements = root.elements();
            setMap(elements.get(0),map,"//@"+elements.get(0).getName());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void setMap(Element element,Map<String,Node> map,String index){
        //加个map来进行同级元素区分
        Map<String,Integer> same = new HashMap<String,Integer>();
        Set<String> set = same.keySet();
        List<Element> list = element.elements();
        Iterator<Element> it = list.iterator();
        int n = 0;
        while (it.hasNext()){
            Element e = it.next();
            String newIndex = "";
            String name = e.getName();
            if(set.contains(name)){
                n = same.get(name)+1;
                newIndex = index+"/@"+name+"."+n;
                same.put(name,n);
            }else {
                newIndex = index+"/@"+name+"."+n;
                same.put(name,n);
            }
            n = 0;
            e.addAttribute("index",newIndex);
            map.put(newIndex,e);
            setMap(e,map,newIndex);
        }
    }


    public static void getTargetInFlow(){
        try {
            Map<String,Node> map = getMap(PathConstants.GEN_IFML_HOME);

            Set<String> set = map.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()){
                String index = it.next();
                if(index.equals("document"))
                    continue;
                Element e = (Element) map.get(index);
                String targetInteractionFlowElement = e.attributeValue("targetInteractionFlowElement");
                if(targetInteractionFlowElement!=null){
                    //输出的index就是targetInteractionFlowElement有值的
                    //System.out.println("index:"+e.attributeValue("index"));
                    TargetInteractionFlow targetInteractionFlow = new TargetInteractionFlow();
                    targetInteractionFlow.setTargetInteractionFlowElement(e.attributeValue("targetInteractionFlowElement"));
                    //去掉字符串末尾多出来的“/”
                    targetInteractionFlow.setFatherIndex(e.attributeValue("index"));
                    targetInteractionFlowList.add(targetInteractionFlow);
                }

            }
            /*for(int i=0;i<targetInteractionFlowList.size();i++){
                System.out.println("targetInteractionFlowElement: "+targetInteractionFlowList.get(i).getTargetInteractionFlowElement()+
                        "父元素："+targetInteractionFlowList.get(i).getFatherIndex());
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void traversal(Map<String,Node> map){
        Iterator<Map.Entry<String, Node>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String, Node> entry = iterator.next();
            System.out.println(entry.getKey());
        }
    }
    public static String getInteractionFlow(int index){
        String result ="";
        for(int i=0;i<targetInteractionFlowList.size();i++){;
            String[] position = targetInteractionFlowList.get(i).getTargetInteractionFlowElement().split("\\.");

            if(position[1].equals(index+"")) {
                result += targetInteractionFlowList.get(i).getFatherIndex()+" ";
            }
        }
        return result;
    }

    public static void printFlow(){
        for(int i=0;i<targetInteractionFlowList.size();i++){
            System.out.println(targetInteractionFlowList.get(i).getFatherIndex()+"***"
            +targetInteractionFlowList.get(i).getTargetInteractionFlowElement());
        }
    }



}
